package com.zh.kotlin_mvvm.ui

import android.os.Bundle
import android.view.KeyEvent
import com.tencent.smtt.export.external.interfaces.SslError
import com.tencent.smtt.export.external.interfaces.SslErrorHandler
import com.tencent.smtt.sdk.WebSettings
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import com.zh.common.base.BaseActivity
import com.zh.kotlin_mvvm.databinding.ActivityX5Binding

class X5Activity : BaseActivity<ActivityX5Binding>() {

    override fun initView(savedInstanceState: Bundle?) {
        settings
//        viewBinding.webView.loadUrl("https://aic.oceanengine.com/workbench?bpId=1668344641768455");
//        viewBinding.webView.loadUrl("https://a5batti.xyz");
    }

    private val settings: Unit
        get() {
            val settings = viewBinding.webView.settings
            //扩大比例的缩放
            settings.apply {
                useWideViewPort = true
                // 设置可以支持缩放
                setSupportZoom(true)
                builtInZoomControls = true
                // 这个解决跨域的问题 - 不安全
                allowFileAccess = true
                //自适应屏幕
                layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
                loadWithOverviewMode = true
                //支持javascript
                javaScriptEnabled = true
                //支持通过JS打开新窗口
                javaScriptCanOpenWindowsAutomatically = true
                //关闭缓存
                cacheMode = WebSettings.LOAD_NO_CACHE
//                setAppCacheEnabled(false)
                domStorageEnabled = true
                databaseEnabled = true
            }
            viewBinding.webView.webViewClient = object : WebViewClient() {
                override fun onReceivedSslError(
                    view: WebView,
                    handler: SslErrorHandler,
                    error: SslError
                ) {
                    /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
                    }*/
                }

                override fun onPageFinished(view: WebView, url: String) {
                    super.onPageFinished(view, url)

                }
            }
        }

    override fun onPause() {
        super.onPause()
        viewBinding.webView.onPause()
    }

    override fun onResume() {
        super.onResume()
        viewBinding.webView.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        viewBinding.webView.removeAllViews()
        viewBinding.webView.destroy()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (viewBinding.webView.canGoBack()) {
                viewBinding.webView.goBack()
                return true
            }
        }
        return super.onKeyDown(keyCode, event)
    }
}